#!/usr/bin/python  
# encoding:gbk
# this script is used to make some ftp operations more convenient  
# add upload and download operations  20111210 version0.1  
  
import sys, os, ftplib, socket, re, shutil, stat, datetime, calendar, time
from datetime import date
  
CONST_HOST = "ftp.XXXXXXXXXX.com"  
CONST_USERNAME = "cfdst"  
CONST_PWD = "cfdst1"  
CONST_BUFFER_SIZE = 8192  
  
# COLOR_NONE = "\033[m"  
# COLOR_GREEN = "\033[01;32m"  
# COLOR_RED = "\033[01;31m"  
# COLOR_YELLOW = "\033[01;33m"  

def getdateformat():
    from datetime import date
    todayStr = date.today().strftime("%Y%m%d")
    return todayStr
  
def connect():  
  try:  
    ftp = ftplib.FTP(CONST_HOST)  
    ftp.login(CONST_USERNAME, CONST_PWD)
    ftp.set_debuglevel(2)  # set debug mode               
    ftp.cwd('data')  # change dir
    return ftp  
  except socket.error, socket.gaierror:  
    print("FTP is unavailable,please check the host,username and password!")  
    sys.exit(0)  
  
def disconnect(ftp):  
  ftp.quit()

def upload(ftp, filename):
  f = open(filename, "rb")
  try:  
      ftp.storbinary("STOR %s" % filename, f, CONST_BUFFER_SIZE) 
  except ftplib.error_perm:  
    return False  
  return True

def multiupload(ftp):
    # make new dir
    localdir = 'C:\\temp\\' + 'upload' + getdateformat()
    if os.path.isdir(localdir):
        print(localdir, " already exists, will delete now ")
    os.system('rd /S /Q ' + localdir)
    os.mkdir(localdir)
    print(localdir, " created ")

    # open uploaded file list
    fileHeadle = open("upload.txt", 'rb')
    textlist = fileHeadle.readlines()

    for line in textlist:
        # print line,
        if not line.strip():  # delete blank line
            continue
        else:
            line = line.strip()
            shutil.copy(line, localdir)
    
    localnames = os.listdir(localdir)
    print '>>>>>>>>>>>>>>>>>> remote dir is ' + ftp.pwd()
    os.chdir(localdir)
    print '>>>>>>>>>>>>>>>>>> local working dir is ' + os.getcwd()
    
    try:
        for index, item in enumerate(localnames):
            print '\n>>>>>>>>>>>>>>>>>> uploading file [' + str(index) + ']: ' + item
            ftp.storbinary('STOR ' + item , (open(item, 'rb')) , CONST_BUFFER_SIZE)
    except ftplib.error_perm:  
        return False    
    return True
  
def download(ftp, filename):  
  f = open(filename, "wb").write  
  try:  
      ftp.retrbinary("RETR %s" % filename, f, CONST_BUFFER_SIZE) 
  except ftplib.error_perm:  
    return False  
  return True  

def multidownload(ftp):  
    # make new dir
    localdir = 'C:\\temp\\' + 'download' + getdateformat()
    if os.path.isdir(localdir):
        print(localdir, " already exists, will delete now ")
    os.system('rd /S /Q ' + localdir)
    os.mkdir(localdir)
    print(localdir, " created ")

    source = open("download.txt", 'rb')
    fileNames = source.readlines()
    
    print '>>>>>>>>>>>>>>>>>> remote dir is ' + ftp.pwd()
    os.chdir(localdir)
    print '>>>>>>>>>>>>>>>>>> local working dir is ' + os.getcwd()

    try:
        for index, item in enumerate(fileNames):
            if not item.strip():  # delete blank line
                continue
            else:
                item = item.strip()
                print '\n>>>>>>>>>>>>>>>>>> downloading file [' + str(index) + ']: ' + 'RETR ' + item
                with open(item, 'wb') as f:
                    ftp.retrbinary('RETR ' + item, f.write, CONST_BUFFER_SIZE)
    except ftplib.error_perm:  
        return False
    return True

 
#def help():  
#  print("help info:")  
#  print("[./ftp.py p filenameA filenameB] ----> upload file into ftp site")  
#  print("[./ftp.py g filenameA filenameB] ----> get file from ftp site")
#  print("[./ftp.py u filename] ----> upload multiple files into ftp site")  
#  print("[./ftp.py d filename] ----> download multiple files from ftp site")  
#  print("[./ftp.py h] ----> show help info")  
#  print("[other params are invalid]")  
  
#def main():  
#  args = sys.argv[1:]  
#  # args = 'd'  
#  if len(args) == 0:  
#    print("Params needed!")  
#    sys.exit(0)  
#  
#  ftp = connect()  
#  
#  if args[0] == "p":  
#    f_list = args[1:]  
#    for up_file in f_list:  
#      if not os.path.exists(up_file):  
#        print(("UPLOAD: %s " + "FAILED" + "  :file not exist") % up_file)  
#        continue  
#      elif not os.path.isfile(up_file):  
#        print(("UPLOAD: %s " + "FAILED" + "  :%s is not a file") % (up_file, up_file))  
#        continue  
#  
#      if upload(ftp, up_file):
#        print(("UPLOAD: %s " + "SUCCESS") % up_file)  
#      else:  
#        print(("UPLOAD: %s " + "FAILED") % up_file)
#
#  if args[0] == "u":  
#    if multiupload(ftp):
#      print("UPLOAD SUCCESS")
#    else:  
#      print("UPLOAD FAILED")
#
#  elif args[0] == "g":  
#    f_list = args[1:]  
#    for down_file in f_list:  
#      if not find(ftp, down_file):  
#        print(("DOWNLOAD: %s " + "FAILED" + "  :%s is not in the ftp site") % (down_file, down_file))  
#        continue  
#      if download(ftp, down_file):
#        print(("DOWNLOAD: %s " + "SUCCESS") % down_file)
#      else:  
#        print(("DOWNLOAD: %s " + "FAILED") % down_file)
#        
#  elif args[0] == "d":  
#    if multidownload(ftp):
#      print("DOWNLOAD SUCCESS")
#    else:  
#      print("DOWNLOAD FAILED")
#      
#  elif args[0] == "l":  
#    list(ftp)  
#  elif args[0] == "f":  
#    f_list = args[1:]  
#    for f_file in f_list:  
#      if find(ftp, f_file):  
#        print(("SEARCH: %s " + "EXIST") % f_file)  
#      else:  
#        print(("SEARCH: %s " + "NOT EXIST") % f_file)  
#  
#  elif args[0] == "h":  
#    help()  
#  else:  
#    print("args are invalid!")  
#    help()  
#  
#  disconnect(ftp)  

def uploadZip():
    today = date.today().strftime("%Y%m%d")
    file1 = r'\\XXXXXXXXXX\Import' + today + '.zip'       
    file2 = r'\\XXXXXXXXXX\OE' + today + '.zip'   
    
    local_directory = r'C:' + os.sep + 'liveupdate' + today
    print local_directory
    if os.path.isdir(local_directory):
        print(local_directory, " already exists, will delete now ")
    os.system('rd /S /Q ' + local_directory)
        
    os.mkdir(local_directory)

    shutil.copy2(file1, local_directory)
    shutil.copy2(file2, local_directory)
    
    importFile = local_directory + '\\' + 'Import' + today + '.zip'
    oeFile = local_directory + '\\' + 'OE' + today + '.zip'

    ftp = connect()
    
    localnames = os.listdir(local_directory)
    print '>>>>>>>>>>>>>>>>>> remote dir is ' + ftp.pwd()
    os.chdir(local_directory)
    print '>>>>>>>>>>>>>>>>>> local working dir is ' + os.getcwd()
    
    try:
        for index, item in enumerate(localnames):
            print '\n>>>>>>>>>>>>>>>>>> uploading file [' + str(index) + ']: ' + item
            ftp.storbinary('STOR ' + item , (open(item, 'rb')) , CONST_BUFFER_SIZE)
    except ftplib.error_perm:  
        return False    
    return True

def downloadZip():
    today = date.today().strftime("%Y%m%d")
    localdir = 'C:\\temp\\' + 'liveupdate' + today
    if os.path.isdir(localdir):
        print(localdir, " already exists, will delete now ")
    os.system('rd /S /Q ' + localdir)
    os.mkdir(localdir)
    print(localdir, " created ")

    fileNames = ['Import' + today + '.zip', 'OE' + today + '.zip']

    ftp = connect()
    print '>>>>>>>>>>>>>>>>>> remote dir is ' + ftp.pwd()
    os.chdir(localdir)
    print '>>>>>>>>>>>>>>>>>> local working dir is ' + os.getcwd()

    try:
        for index, item in enumerate(fileNames):
            if not item.strip():  # delete blank line
                continue
            else:
                item = item.strip()
                print '\n>>>>>>>>>>>>>>>>>> downloading file [' + str(index) + ']: ' + 'RETR ' + item
                with open(item, 'wb') as f:
                    ftp.retrbinary('RETR ' + item, f.write, CONST_BUFFER_SIZE)
    except ftplib.error_perm:  
        return False
    return True

if __name__ == "__main__":
    # main()
    # uploadZip()
    downloadZip()
